/**
 * Copyright(c) 2014 Xunton Solutions
 *
 * History:
 *   15-9-18 下午3:41 Created by dwzhang
 */
package com.jade.bss.weixin.api.protocol.xml;

import java.util.Arrays;
import java.util.Map;

import org.apache.commons.codec.digest.DigestUtils;

/**
 * 签名工具类。
 *
 * @author <a href="mailto:dwzhang@xunton.com">dwzhang</a> 
 * @version 1.0 15-9-18 下午3:41
 */
public class SignUtils
{
    public static String sign(Map<String, Object> params, String apiKey)
            throws Exception
    {
        String[] keys = params.keySet().toArray(new String[0]);
        Arrays.sort(keys);
        String tmp = "";
        for (String key : keys) {
            Object o = params.get(key);
            if (o != null) {
                tmp += "&" + key + "=" + o;
            }
        }
        tmp = tmp.substring(1) + "&key=" + apiKey;
        return DigestUtils.md5Hex(tmp).toUpperCase();
    }

    public static boolean checkSignature(String token, String timestamp, String nonce, String signature)
            throws Exception
    {
        String[] params = new String[3];
        params[0] = token;
        params[1] = timestamp;
        params[2] = nonce;

        Arrays.sort(params);
        String key = params[0] + params[1] + params[2];
        String tmp = DigestUtils.sha1Hex(key);
        return signature.equalsIgnoreCase(tmp);
    }
}
